clear
capture restore
set scheme cleanplots, perm

* SET DIRECTORIES
global home "..."

global data "$home/Data/"
global output "$home/Output/"

cd $home

*SET CONTROL VARIABLES
local firm_controls "log_salesg_real_1lag_std size_assets_1lag_std liquidity_1lag_std pcmq_1lag_std recpay2yq_1lag_std d2aq_1lag_std ln_market_cap_q_1lag_std tobins_q_1lag_std lev_d2c_1lag_std dd_1lag_std age_1lag_std i.sector i.fqtr"

local agg_controls "lngdp inflation unemp nasdaq fedfunds"

*************
***Options***
*************
*Set ivol measure to use as baseline
local matur m1545
*Set mp shock to use as baseline
local mps ff4_d

* Set the LP details ========================================================================
*# periods to compute the responses foreach
local hor = 20
*# lags of "endogenous" variables 
local lagy = 4 
*# lags of "shock"
local lage = 0 

********************************************************************************
********************************************************************************
********************************************************************************
*Read-in ivol data (contains all trading days for Compustat firms)
use "${data}Compustat_Quarterly_Final", clear

local n = 20

*Set panel data
xtset firmid ts_qtr

*Flag sample for those in at least n quarters
bysort gvkey pre_crisis: egen obs_num_temp = count(gvkey) if pre_crisis
bysort gvkey: egen obs_num = max(obs_num_temp)

*Flag outliers (bottom/top 0.5%) for investment
_pctile investment_intensive if pre_crisis, p(.5 99.5)
gen 	investment_outlier = (investment_intensive<r(r1)|investment_intensive>r(r2))

gen sample_period=(pre_crisis==1)

gen in_sample = (obs_num>=`n' & !missing(obs_num) & investment_outlier==0 & sample_period)

********************************************************************************
*Set panel data
xtset firmid ts_qtr

gen ivol_`matur'_std = ivol_`matur'
gen vix_eoq_std = vix_eoq
gen dd_std = dd
gen age_1lag_std = age

rename age age_1lag

***Standardize quarterly Compustat variables and lagged ivol level
foreach i in dd_1lag age_1lag log_salesg_real_1lag size_assets_1lag liquidity_1lag pcmq_1lag recpay2yq_1lag d2aq_1lag ln_market_cap_q_1lag tobins_q_1lag lev_d2c_1lag ivol_`matur' vix_eoq {

	*Pre-Crisis Standardization
	drop `i'_std
	qui: sum `i' if in_sample
	gen `i'_std = (`i' - r(mean)) / r(sd)
	
}

*Standardize ivol and dd
_pctile ivol_`matur' if in_sample, percentiles(30 70)
gen ivol_`matur'_hi2lo = (ivol_`matur' - r(r1)) / (r(r2) -  r(r1))

_pctile dd  if in_sample, percentiles(30 70)
gen dd_hi2lo = (dd - r(r1)) / (r(r2) -  r(r1))

*Standardize mps to unit standard deviation & positive is expansionary
gen `mps'=`mps'_shock_qtr
egen date_tag=tag(ts_qtr)

sum `mps' if pre_crisis & date_tag
replace `mps' = `mps'/r(sd)
********************************************************************************
*Prepare local projection variables
********************************************************************************
xtset firmid ts_qtr

*Use the inflation-adjusted versions of dependent variables, if applicable
foreach i in niq ivltq ivstq invtq intanq tanq xrdq saleq K_int K_int_Know K_int_Org K_int_offBS K_int_onBS {
	
	drop `i'
	rename `i'_real `i'
 
}


foreach var in capital_stock K_int_Know_qtr K_int_Org_qtr ppentq {
*	foreach var in capital_stock niq ivltq ivstq invtq current_total_orig liquidity intanq tanq K_int K_int_Know K_int_Org K_int_offBS K_int_onBS K_tot xrdq saleq tobins_q_wins q_tot_wins K_phys_qtr K_phys_qtr_proxy K_int_qtr K_int_onBS_qtr K_int_offBS_qtr K_int_Know_qtr K_int_Org_qtr K_tot_qtr {
	forvalues h =   0/`hor' {
		 gen `var'`h' = (ln(f`h'.`var') - ln(l.`var')) * 100
}
}

*Create time variable for DK SEs
xtset
egen time=group(ts_qtr)
xtset firmid time

drop if !in_sample

	foreach var in capital_stock { 

	eststo clear
		
	cap gen qtrs = _n-1 if _n<=`hor'+1
	cap gen zero =  0 	if _n<=`hor'+1
	cap gen b_mps = 0
	cap gen u_mps = 0
	cap gen d_mps = 0
	cap gen uu_mps = 0
	cap gen dd_mps = 0

	cap gen b_ivol = 0
	cap gen u_ivol = 0
	cap gen uu_ivol = 0 
	cap gen d_ivol = 0
	cap gen dd_ivol = 0

	cap gen b_mpsI = 0
	cap gen u_mpsI = 0
	cap gen uu_mpsI = 0
	cap gen d_mpsI = 0
	cap gen dd_mpsI = 0

	cap gen b_intEff = 0
	cap gen u_intEff = 0
	cap gen d_intEff = 0
	cap gen uu_intEff = 0
	cap gen dd_intEff = 0

	cap gen nobs = 0
	
	********************************************************************************
	*INVESTMENT REGRESSIONS
	********************************************************************************

	*1. Investment on mps (plus interaction with ivol level)
	forvalues h = 0/`hor' {

		quietly: reghdfe `var'`h' `mps' L.ivol_`matur'_hi2lo  c.`mps'#c.L.ivol_`matur'_hi2lo  `firm_controls' l(1/`lagy').(`agg_controls') if in_sample, a(firmid) vce(cluster time,dkraay(16)) old
		replace b_mps = _b[`mps']                     	if _n == `h'+1
		replace u_mps = _b[`mps'] + 1.645* _se[`mps']  	if _n == `h'+1
		replace d_mps = _b[`mps'] - 1.645* _se[`mps']  	if _n == `h'+1
		replace uu_mps = _b[`mps'] + _se[`mps']  	if _n == `h'+1
		replace dd_mps = _b[`mps'] - _se[`mps']  	if _n == `h'+1	
		
		replace b_ivol = _b[L.ivol_`matur'_hi2lo ]                     			if _n == `h'+1
		replace u_ivol = _b[L.ivol_`matur'_hi2lo ] + 1.645* _se[L.ivol_`matur'_hi2lo ]  	if _n == `h'+1
		replace d_ivol = _b[L.ivol_`matur'_hi2lo ] - 1.645* _se[L.ivol_`matur'_hi2lo ]  	if _n == `h'+1	
		replace uu_ivol = _b[L.ivol_`matur'_hi2lo ] + _se[L.ivol_`matur'_hi2lo ]  	if _n == `h'+1
		replace dd_ivol = _b[L.ivol_`matur'_hi2lo ] - _se[L.ivol_`matur'_hi2lo ]  	if _n == `h'+1	
		
		lincom _b[`mps'] + _b[c.`mps'#c.L.ivol_`matur'_hi2lo ]
		replace b_intEff = r(estimate)                  if _n == `h'+1
		replace u_intEff = r(estimate) + 1.645* r(se)  	if _n == `h'+1
		replace d_intEff = r(estimate) - 1.645* r(se) 	if _n == `h'+1	
		replace uu_intEff = r(estimate) + r(se)  	if _n == `h'+1
		replace dd_intEff = r(estimate) - r(se) 	if _n == `h'+1	
		
		replace b_mpsI = _b[c.`mps'#c.L.ivol_`matur'_hi2lo ]                     			if _n == `h'+1
		replace u_mpsI = _b[c.`mps'#c.L.ivol_`matur'_hi2lo ] + 1.645* _se[c.`mps'#c.L.ivol_`matur'_hi2lo ]  	if _n == `h'+1
		replace d_mpsI = _b[c.`mps'#c.L.ivol_`matur'_hi2lo ] - 1.645* _se[c.`mps'#c.L.ivol_`matur'_hi2lo ]  	if _n == `h'+1	
		replace uu_mpsI = _b[c.`mps'#c.L.ivol_`matur'_hi2lo ] + _se[c.`mps'#c.L.ivol_`matur'_hi2lo ]  	if _n == `h'+1
		replace dd_mpsI = _b[c.`mps'#c.L.ivol_`matur'_hi2lo ] - _se[c.`mps'#c.L.ivol_`matur'_hi2lo ]  	if _n == `h'+1			
		replace nobs = e(N)                        						if _n == `h'+1	
		di e(N)
		di _b[c.`mps'#c.L.ivol_`matur'_hi2lo ] 
		eststo
		
	}

	* Plot the Investment response
	twoway (rarea d_intEff u_intEff qtrs, fc(red%25) lw(none) lpattern(solid)) ///
	(rarea dd_intEff uu_intEff qtrs, fc(red%50) lw(none) lpattern(solid)) ///
	(rarea d_mps u_mps qtrs, fc(blue%25) lw(none) lpattern(solid)) ///
	(rarea dd_mps uu_mps qtrs, fc(blue%50) lw(none) lpattern(solid)) ///
	(line b_intEff qtrs, lcolor(red) lpattern(solid) lwidth(thick) xlabel(,labsize(medlarge) nogrid) ylabel(,labsize(medlarge) nogrid)) ///
	(line b_mps qtrs, lcolor(blue) lpattern(solid) lwidth(thick)) /// 
	(line zero qtrs, lcolor(black)) if !missing(qtrs), legend(off) ///
	ytitle("Percent", size(medlarge)) xtitle("Quarter", size(medlarge)) ///
	graphregion(color(white)) plotregion(color(white))

	graph export "${output}figure1_panelA.pdf", replace

	twoway (rarea u_mpsI d_mpsI qtrs, fcolor(gs14) lcolor(gs14) lw(none) lpattern(solid) xlabel(,labsize(medlarge) nogrid) ylabel(,labsize(medlarge) nogrid)) ///
	(rarea uu_mpsI dd_mpsI qtrs, fcolor(gs8) lcolor(gs8) lw(none) lpattern(solid)) ///
	(line b_mpsI qtrs, lcolor(black) lpattern(solid) lwidth(thick)) /// 
	(line zero qtrs, lcolor(black)) if !missing(qtrs), legend(off) ///
	ytitle("Percent", size(medlarge)) xtitle("Quarter", size(medlarge)) ///
	graphregion(color(white)) plotregion(color(white))

	graph export "${output}figure1_panelB.pdf", replace
	
	drop qtrs zero b_mps u_mps d_mps b_ivol u_ivol d_ivol b_mpsI u_mpsI uu_mpsI d_mpsI dd_mpsI b_intEff uu_ivol dd_ivol nobs
	
	eststo clear	
}
